// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
module.exports = {
	_before: function() { // 通用预处理器
		// this.param = this.getParam();
		try {
			this.param = JSON.parse(this.getHttpInfo().body);
			console.log("_before", JSON.stringify(this.param));
		} catch (e) {
			console.log("获取参数异常:", JSON.stringify(e));
		}
	},

	 loginUser: async function(param) {
		 if (!(this.param && this.param.lat && this.param.lon)) {
		 	if (!(param && param.lat && param.lon)) {
		 		return {
		 			errCode: 'param.lat_IS_NULL',
		 			errMsg: 'param.lat/lon参数不能为空'
		 		}
		 	} else {
		 
		 		this.param = param;
		 	}
		 }
		//event为客户端上传的参数
		console.log('event : ', event)
		// 查询数据库
		const w24hCollection = db.collection('HS24HCityWeather');
		let dbhWeather = await w24hCollection.where({
			"location": location
		}).get();
		const {
			openId,
			isNature
		} = event;
		const db = uniCloud.database();
		const collection = db.collection('users');
		let res = await collection.where({
			"openId": openId
		}).get();
		//返回数据给客户端
		console.log("登录:", res.data.length);
		if (res.data && res.data.length > 0) {
			console.log("登录:", res.data[0]);
			return res.data[0];
		} else {
			let timezone = 8; //目标时区时间，东八区   东时区正数 西市区负数
			let offset_GMT = new Date().getTimezoneOffset(); // 本地时间和格林威治的时间差，单位为分钟
			let nowDate = new Date().getTime(); // 本地时间距 1970 年 1 月 1 日午夜（GMT 时间）之间的毫秒数
			let targetDate = new Date(nowDate + offset_GMT * 60 * 1000 + timezone * 60 * 60 * 1000);
			let nowTime = targetDate.getFullYear() + "-" + parseInt(targetDate.getMonth() + 1) + "-" + targetDate
				.getDate() + " " + targetDate.getHours() + ":" + targetDate.getMinutes() + ":" + targetDate
				.getSeconds();
			//时间戳为10位需*1000，时间戳为13位的话不需乘1000
			let user = {
				openId: openId,
				isNature: isNature,
				vipLevel: 0,
				expireDate: 0,
				creatTime: nowTime
			}
			let addRes = await collection.add(user);
			console.log("注册addRes:", addRes);
			let res = await collection.where({
				"openId": openId
			}).get();
			if (res.data && res.data.length > 0) {
				console.log("注册:", res);
				return res.data[0];
			}
		}
	},
}